package com.sgb.capital.view.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider;
import com.sgb.capital.R;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.CommoditylistFragmentBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.CommodityBean;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.ui.adapter.CommodityListAdapter;
import com.sgb.capital.viewmodel.CommodityModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/11/17 0016
 * 说明:商品询价
 */
public class CommodityListFragment extends AppLazyFragment {

    private CommoditylistFragmentBinding mBinding;
    private CommodityModel mModel;

    private boolean isLoadMore = false; //是否加载更多
    private boolean isEnableLoadMore = false;//是否能加载更多
    private CommodityListAdapter mAdapter;
    private int mPos;
    private String mType;
    private int mPage;

    /**
     * @param type
     * @return
     */
    public static CommodityListFragment newInstance(String type) {
        CommodityListFragment fragment = new CommodityListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.commoditylist_fragment, container, false);
        return mBinding.getRoot();
    }


    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        Bundle arguments = getArguments();
        mType = arguments.getString("type", "报价");
        System.out.println("type=="+mType);
        mModel = new ViewModelProvider(this).get(CommodityModel.class);
        mBinding.rv.setLayoutManager(new LinearLayoutManager(Utils.getContext()));
        mAdapter = new CommodityListAdapter(null);
        mAdapter.mType = mType;
        View empty = LayoutInflater.from(getActivity()).inflate(R.layout.capital_layout_empty_view, mBinding.rv, false);
        mAdapter.setEmptyView(empty);
        mBinding.rv.setAdapter(mAdapter);
    }


    @Override
    protected void onLazyLoad() {
        mPage = 1;
        mAdapter.mPos = mPos;
        if (mPos == 0) {
            if (mType.contains("报价")) {
                mModel.receivedQuotedList(getActivity(), 10, mPage);
            } else {
                mModel.receivedEnquiryList(getActivity(), 10, mPage);
            }
        } else {
            if (mType.contains("报价")) {
                mModel.publishQuotedEnquiryList(getActivity(), 10, mPage);
            } else {
                mModel.enquiryList(getActivity(), 10, mPage);
            }
        }
    }

    @Override
    public void initListener() {
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            CommodityBean.ListDTO data = mAdapter.getData().get(position);
            Utils.sendMsg(Constants.EVENT_CLICK, data);
        });
        mBinding.srl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                mPage++;
                if (mType.contains("报价")) {
                    if (mPos == 0) {
                        mModel.receivedQuotedList(getActivity(), 10, mPage);
                    } else {
                        mModel.publishQuotedEnquiryList(getActivity(), 10, mPage);
                    }
                } else {
                    if (mPos == 0) {
                        mModel.receivedEnquiryList(getActivity(), 10, mPage);
                    } else {
                        mModel.enquiryList(getActivity(), 10, mPage);
                    }
                }
                mBinding.srl.finishLoadMore(500);
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                isLoadMore = false;
                mPage = 1;
                if (mType.contains("报价")) {
                    if (mPos == 0) {
                        mModel.receivedQuotedList(getActivity(), 10, mPage);
                    } else {
                        mModel.publishQuotedEnquiryList(getActivity(), 10, mPage);
                    }
                } else {
                    if (mPos == 0) {
                        mModel.receivedEnquiryList(getActivity(), 10, mPage);
                    } else {
                        mModel.enquiryList(getActivity(), 10, mPage);
                    }
                }
                mBinding.srl.finishRefresh(500);
            }
        });
        mBinding.srl.setScrollBoundaryDecider(new ScrollBoundaryDecider() {
            @Override
            public boolean canRefresh(View content) {
                if (mBinding.rv == null) return false;
                return mBinding.rv.computeVerticalScrollOffset() == 0;
            }

            @Override
            public boolean canLoadMore(View content) {
                if (mBinding.rv == null) return false;
                int scrollRange = mBinding.rv.computeVerticalScrollRange();
                int scrollOffset = mBinding.rv.computeVerticalScrollOffset();
                int scrollExtent = mBinding.rv.computeVerticalScrollExtent();
                int height = mBinding.rv.getHeight();
                if (height > scrollRange) {
                    return false;
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent;
            }
        });
    }

    @Override
    public void initObserve() {
        mModel.mCommodityBean.observe(this, data -> {
            if (data == null) return;
            isEnableLoadMore = data.list.size() >= 10;
            if (isLoadMore) {
                mAdapter.addData(data.list);
            } else {
                mAdapter.setNewInstance(data.list);
            }
            Utils.sendMsg(Constants.EVENT_REFRESH_COUNT, data.totalRow);
        });
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_REFRESH_COMMODITY:
                Bean bean = (Bean) event.data;
                mPos = bean.posFirst;
                if (mType.contains("报价")) {
                    if (bean.posSecond == 2) {
                        onLazyLoad();
                    }
                } else {
                    if (bean.posSecond == 0) {
                        onLazyLoad();
                    }
                }
                break;
        }
    }
}